# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

# 易付
APP_CONF = {
    '93522935': {  # dwc 付宝2.5%（100---5万）D0结算
        'API_KEY': 'rU9mloiYLFOWbuoXO33brByby6n3uskm',
        'gateway': 'http://120.79.219.170:44192/alipay/transferJson',
        'query_gateway': 'http://120.79.219.170:44192/alipay/queryOrder',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


# MD5(商户号+商户秘钥+交易金额+商户端订单号+发起时间(格式为：yyyyMMddHHmmss)).toUpperCase();
def generate_sign(parameter, key):
    s = '{}{}{}{}{}'.format(parameter['spid'], key, parameter['tran_amt'],
                            parameter['sp_billno'], parameter['tran_time'])
    _LOGGER.info('yifupay sign : %s', s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


# MD5(商户号+商户秘钥+平台订单号+支付金额+商户订单号). toUpperCase();
def generate_notify_sign(parameter, app_id, key):
    s = '{}{}{}{}{}'.format(app_id, key, parameter['listid'],
                            parameter['tran_amt'], parameter['sp_billno'])
    _LOGGER.info('yifupay notify sign : %s', s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


# MD5(商户号+商户秘钥+商户订单号+平台订单号). toUpperCase();
def generate_query_sign(parameter, key):
    s = '{}{}{}{}'.format(parameter['spid'], key, parameter['sp_billno'],
                          parameter['listid'])
    _LOGGER.info('yifupay query sign : %s', s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


# MD5(商户号+秘钥+商户订单号+平台订单号+交易金额+订单创建时间(spid+privateKey+spBillNo+listid+tran_amt+ create_time)
def generate_rep_query_sign(parameter, key):
    s = '{}{}{}{}{}{}'.format(parameter['spid'], key, parameter['sp_billno'],
                              parameter['listid'], parameter['tran_amt'], parameter['create_time'])
    _LOGGER.info('yifupay rep query sign : %s', s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(params, app_id, key):
    sign = params.pop('sign')
    calculated_sign = generate_notify_sign(params, app_id, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("yifupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def verify_query_sign(params, key):
    sign = params.pop('sign')
    calculated_sign = generate_rep_query_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("yifupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    """ 支付宝手机网页支付:1
        支付宝转账支付:2 """
    if service == 'alipay':
        return '2'
    return '2'


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info['service']
    parameter_dict = OrderedDict((
        ('sign_type', 'MD5'),
        ('spid', str(app_id)),
        ('notify_url', '{}/pay/api/{}/yifupay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('sp_billno', str(pay.id)),
        ('pay_type', _get_pay_type(service)),
        ('tran_time', local_now().strftime('%Y%m%d%H%M%S')),
        ('tran_amt', '%.2f' % pay_amount),
        ('cur_type', 'CNY'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    url = _get_gateway(app_id)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    _LOGGER.info("yifupay create: url: %s, %s", url, json.dumps(parameter_dict))
    response = requests.post(url, data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("yifupay create: response: %s", response.text)
    data = json.loads(response.text)
    if data['listid']:
        order_db.fill_third_id(str(pay.id), data['listid'])
    return {'charge_info': data['iosAliPayUrl']}


def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("yifupay notify data: %s", data)
    verify_notify_sign(data, app_id, api_key)
    pay_id = data['sp_billno']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('yifupay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id  # 商户编号
    trade_status = str(data['tran_state'])
    trade_no = data['listid']
    total_fee = float(data['tran_amt'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    # 支付状态：0-失败；1-成功
    if trade_status == '1' and total_fee > 0.0:
        _LOGGER.info('yifupay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('sign_type', 'MD5'),
        ('spid', app_id),
        ('sp_billno', str(pay_id)),
        ('listid', pay_order.third_id),
    ))
    parameter_dict['sign'] = generate_query_sign(parameter_dict, api_key)
    _LOGGER.info('yifupay query data, %s', json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=10)
    _LOGGER.info('yifupay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)

        verify_query_sign(data, api_key)

        mch_id = pay_order.mch_id
        trade_status = str(data['state'])
        total_fee = float(data['tran_amt'])
        trade_no = str(data['listid'])
        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        """
        交易状态
        1-创建未支付；
        2-已支付-待回调；
        3-已支付-回调失败
        4-已支付-已回调；
        5-订单关闭
        """
        if trade_status in ['2', '3', '4'] and total_fee > 0.0:
            check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('yifupay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
